from fastapi import Request
from apps.message.models import BrowserChoice, SystemChoice
from user_agents import parse
from ip2region.ip2regin import searcher


def get_client_info(request: Request) -> dict:
    user_agent_string = request.headers.get("User-Agent", "")
    user_agent = parse(user_agent_string)

    # 浏览器检测
    browser = BrowserChoice.UNKNOWN
    browser_family = user_agent.browser.family
    if "Chrome" in browser_family:
        browser = BrowserChoice.CHROME
    elif "Firefox" in browser_family:
        browser = BrowserChoice.FIREFOX
    elif "Safari" in browser_family:
        browser = BrowserChoice.SAFARI
    elif "Edge" in browser_family:
        browser = BrowserChoice.EDGE
    elif "IE" in browser_family:
        browser = BrowserChoice.IE

    # 操作系统检测
    system = SystemChoice.UNKNOWN
    os_family = user_agent.os.family
    if "Windows" in os_family:
        system = SystemChoice.WINDOWS
    elif "Mac OS" in os_family:
        system = SystemChoice.MAC
    elif "Linux" in os_family:
        system = SystemChoice.LINUX
    elif "Android" in os_family:
        system = SystemChoice.ANDROID
    elif "iOS" in os_family:
        system = SystemChoice.IOS

    # 获取IP地址
    ip = request.client.host
    x_forwarded_for = request.headers.get("X-Forwarded-For")
    if x_forwarded_for:
        ip = x_forwarded_for.split(",")[0]

    # 获取IP地址的地理位置信息
    location = searcher.search(ip)
    country = location.country
    region = location.region
    city = location.city

    print(f"IP: {ip}, Country: {country}, Region: {region}, City: {city}")

    return {
        "browser": browser,
        "system": system,
        "ip": ip,
        "country": country,
        "region": region,
        "city": city,
    }
